import hashlib
import json
import platform
import urllib
from functools import reduce


# from urllib import parse


def get_platform():
    """获取平台类型

    :return: win，linux，os
    """
    sysstr = platform.system()
    if sysstr == "Windows":
        return "win"
    elif sysstr == "Linux":
        return "linux"
    else:
        return "os"


def is_empty(_str):
    """是否为空或None

    :param _str:字符串
    :return:True or False
    """
    if _str == '' or _str is None:
        return True
    else:
        return False


def model_to_json(model, sort_keys=False):
    """实体转json


    :param model:实体对象
    :param sort_keys:按字母排序
    :return:
    """
    # indent= 4缩进
    # separators = (',', ':') 去掉空格
    return json.dumps(model, ensure_ascii=False, default=lambda obj: obj.__dict__,
                      sort_keys=sort_keys, indent=None, separators=(',', ':'))


def json_to_model(json_str, module_name, class_name):
    """json转换成实体

    :param json_str: json字符串
    :param module_name:模块名称 client.fxg.entity
    :param class_name:类名 FxgModel
    :return:
    """
    if json_str is None or json_str == '':
        raise Exception('json_str 不能为空')

    if module_name is None or module_name == '':
        raise Exception('module_name 不能为空')

    if class_name is None or class_name == '':
        raise Exception('class_name 不能为空')

    try:
        model_dict = json.loads(json_str)
    except:
        try:
            model_dict = json.loads(json.dumps(eval(json_str)))
        except:
            raise Exception('json_str 解析错误')

    try:
        # 使用__import__()导入模块
        ip_module = __import__(module_name, fromlist=True)
        # dir()查看模块属性
        # print(dir(ip_module))
        # 使用getattr()获取imp_module的类
        MyClass = getattr(ip_module, class_name)
        obj = MyClass()
        # 给对象赋值属性
        for key, value in model_dict.items():
            setattr(obj, key, value)
        return obj
    except Exception as e:
        raise Exception('实体转换错误', e)
        # if '__class__' in model_dict:
        #     class_name = model_dict.pop('__class__')
        #     module_name = model_dict.pop('__module__')
        #     module = __import__(module_name)
        #     class_ = getattr(module, class_name)
        #     args = dict((key.encode('ascii'), value) for key, value in model_dict.items())  # get args
        #     inst = class_(**args)  # create new instance
        # else:
        #     inst = model_dict
        # return inst


def array_to_str(arr, split_str):
    r"""使用指定分隔符字符串将数组转换成字符串

    :param: arr: 数组
    :param split_str: 分隔符
    :return:
    """
    return split_str.jion(arr)


def to_md5(source_str):
    """将字符串进行MD5编码

    :param source_str:
    :return:
    """
    if is_empty(source_str):
        raise Exception("source_str 不能为空")
    m = hashlib.md5()
    # 使用md5对象里的update方法md5转换
    m.update(source_str.encode("utf-8"))
    result = m.hexdigest()
    return result


def get_http_param_value(http_str, param_name):
    """获取http地址的参数值

    :param http_str:
    :param param_name:
    :return:
    """
    if is_empty(http_str) and is_empty(param_name):
        raise Exception("http_str 与 param_name 不能为空")

    url = http_str.split('?')
    qs = urllib.parse.parse_qs(url[1])
    for key in qs:
        if key == param_name:
            return qs[key][0]
    return None


def url_encode(data, rep=False):
    r"""url编码

    :param data:url数据字符串
    :param rep: 是否替换*号 java中*号不被url编码
    :return:string
    """
    if is_empty(data):
        raise Exception("data 不能为空")
    result = urllib.parse.quote(data)
    if rep is False:
        return result
    else:
        return result.replace("%2A", "*")


def url_decode(data):
    r"""url解码

    :param data:url数据字符串
    :return:string
    """
    if is_empty(data):
        raise Exception("data 不能为空")
    return urllib.parse.unquote(data)


def float_ceil(num: float, ceil: int):
    if ceil == 0:
        return float('%.0f' % num)
    if ceil == 1:
        return float('%.1f' % num)
    if ceil == 2:
        return float('%.2f' % num)
    if ceil == 3:
        return float('%.3f' % num)


def toHex(str):
    lst = []
    for ch in str:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0' + hv
        lst.append(hv)
    return reduce(lambda x, y: x + y, lst);
